<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page import="org.example.entity.Person" %>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>投票系统 - 新增主题</title>
    <!-- 引入Layui CSS -->
    <%--    <link rel="stylesheet" href="../../css/layui.css">--%>
    <script src="../../js/layui.js"></script>
    <link rel="stylesheet" href="https://cdn.staticfile.org/layui/2.8.17/css/layui.min.css">
    <script src="../../js/jquery-3.7.1.min.js"></script>
    <!-- 引入Font Awesome -->
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <style>
        body {
            background-color: #f8f9fa;
            margin: 0;
            padding: 0;
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
            color: #333;
        }

        .header {
            background-color: #ffffff;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
            padding: 15px 30px;
            display: flex;
            align-items: center;
        }

        .header a {
            color: #333;
            margin-left: 25px;
            text-decoration: none;
            transition: color 0.3s ease;
            font-size: 15px;
        }

        .header a:hover {
            color: #1E9FFF;
        }

        .header > a:first-child {
            margin-left: 0;
        }

        .ml-auto {
            margin-left: auto;
        }

        .admin-container {
            padding: 30px 20px;
            max-width: 1000px;
            margin: 0 auto;
        }

        .form-card {
            background-color: #ffffff;
            border-radius: 16px;
            box-shadow: 0 8px 24px rgba(0, 0, 0, 0.08);
            overflow: hidden;
        }

        .form-header {
            padding: 25px 30px;
            border-bottom: 1px solid #f0f2f5;
        }

        .form-title {
            font-size: 20px;
            font-weight: 600;
            color: #333;
        }

        .form-body {
            padding: 30px;
        }

        .layui-form-item {
            margin-bottom: 24px;
        }

        .layui-form-label {
            width: 120px;
            padding: 9px 0;
            text-align: right;
            color: #666;
            font-weight: 500;
        }

        .layui-input-block {
            margin-left: 150px;
        }

        .layui-input, .layui-textarea {
            border-radius: 8px;
            padding: 8px 12px;
            height: auto;
            border-color: #e0e2e5;
            transition: border-color 0.2s ease;
        }

        .layui-input:focus, .layui-textarea:focus {
            border-color: #1E9FFF !important;
            box-shadow: 0 0 0 2px rgba(30, 159, 255, 0.1);
        }

        .layui-form-radio > i:hover, .layui-form-radioed > i {
            color: #1E9FFF;
        }

        .layui-form-checkbox[lay-skin=primary]:hover i {
            border-color: #1E9FFF;
        }

        .layui-form-checked[lay-skin=primary] i {
            border-color: #1E9FFF;
            background-color: #1E9FFF;
        }

        .layui-form-checked i, .layui-form-checked:hover i {
            border-color: #1E9FFF;
        }

        .layui-btn {
            background-color: #1E9FFF;
            border-radius: 8px;
            padding: 0 24px;
            height: 40px;
            line-height: 40px;
            font-size: 14px;
            font-weight: 500;
            transition: all 0.2s ease;
        }

        .layui-btn:hover {
            background-color: #0d87e6;
            transform: translateY(-1px);
            box-shadow: 0 2px 8px rgba(30, 159, 255, 0.3);
        }

        .layui-btn-primary {
            background-color: #fff;
            border: 1px solid #e0e2e5;
            color: #666;
        }

        .layui-btn-primary:hover {
            border-color: #1E9FFF;
            color: #1E9FFF;
            background-color: #fff;
            transform: translateY(0);
            box-shadow: none;
        }

        .form-footer {
            padding: 20px 30px;
            background-color: #f8f9fa;
            display: flex;
            justify-content: flex-end;
            gap: 15px;
        }

        /* 日期选择器样式 */
        .layui-laydate .layui-this {
            background-color: #1E9FFF !important;
        }

        .layui-laydate-header i:hover, .layui-laydate-header span:hover {
            color: #1E9FFF;
        }

        /* 选项管理样式 */
        .option-item {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 15px;
            padding: 12px;
            border-radius: 8px;
            background-color: #f8f9fa;
            transition: all 0.2s ease;
        }

        .option-item:hover {
            background-color: #f0f2f5;
        }

        .option-index {
            width: 24px;
            height: 24px;
            line-height: 24px;
            text-align: center;
            background-color: #e0e2e5;
            color: #666;
            border-radius: 50%;
            font-size: 12px;
            font-weight: 500;
        }

        .option-input {
            flex-grow: 1;
        }

        .delete-option {
            color: #dc3545;
            cursor: pointer;
            padding: 5px;
            border-radius: 5px;
            transition: all 0.2s ease;
        }

        .delete-option:hover {
            background-color: rgba(220, 53, 69, 0.1);
        }

        #addOptionBtn {
            margin-top: 10px;
            color: #1E9FFF;
            cursor: pointer;
            display: inline-flex;
            align-items: center;
            font-size: 14px;
            font-weight: 500;
            transition: all 0.2s ease;
        }

        #addOptionBtn:hover {
            text-decoration: underline;
        }

        #addOptionBtn i {
            margin-right: 5px;
        }

        /* 响应式调整 */
        @media (max-width: 768px) {
            .admin-container {
                padding: 20px 15px;
            }

            .form-header, .form-body, .form-footer {
                padding: 20px 15px;
            }

            .layui-form-label {
                width: 100%;
                text-align: left;
                padding-bottom: 5px;
            }

            .layui-input-block {
                margin-left: 0;
            }

            .option-item {
                flex-wrap: wrap;
            }

            .option-input {
                width: 100%;
            }
        }

        /* 选项图片上传样式 */
        .option-upload {
            display: flex;
            align-items: center;
            margin-left: 10px;
        }

        .option-upload-btn {
            margin-right: 10px;
            padding: 6px 12px;
            font-size: 12px;
            height: auto;
        }

        .option-preview {
            max-width: 100px;
            max-height: 100px;
            border-radius: 8px;
            display: none;
            object-fit: cover;
            border: 1px solid #e0e2e5;
        }

        #sub {
            display: none;
        }

    </style>
</head>
<body>
<nav class="header">

    <c:if test="${person.level == 1}">
        <a href="${pageContext.request.contextPath}/person/index" class="flex items-center">
            <i class="fa fa-home text-primary text-xl mr-2"></i>
            <span class="font-bold text-lg">用户首页</span>
        </a>
        <a href="${pageContext.request.contextPath}/admin/index" class="flex items-center">
            <i class="fa fa-home text-primary text-xl mr-2"></i>
            <span class="font-bold text-lg">管理员首页</span>
        </a>
    </c:if>
    <c:if test="${person.level == 0}">
        <a href="${pageContext.request.contextPath}/person/index" class="flex items-center">
            <i class="fa fa-home text-primary text-xl mr-2"></i>
            <span class="font-bold text-lg">用户首页</span>
        </a>
    </c:if>

    <div class="ml-auto flex items-center">
        <c:if test="${person == null}">
            <a href="${pageContext.request.contextPath}/views/login.jsp"><i class="fa fa-user-circle mr-2"></i>请先登录</a>
        </c:if>
        <c:if test="${person != null}">
            <a href="${pageContext.request.contextPath}/admin/person/editPerson?pid=${person.pid}"><i
                    class="fa fa-user-circle mr-2"></i>${person.username}</a>
        </c:if>

        <a href="javascript:void(0);" onclick="logout()">退出登录</a>
    </div>
</nav>

<div class="admin-container">
    <div class="form-card">
        <div class="form-header">
            <div class="form-title">新增主题</div>
        </div>

        <form class="layui-form" id="topicForm" action="${pageContext.request.contextPath}/admin/topic/addTopic"
              method="post" enctype="multipart/form-data">
            <div class="form-body">
                <div class="layui-form-item">
                    <label class="layui-form-label">主题标题</label>
                    <div class="layui-input-block">
                        <input type="text" name="title" id="title" required lay-verify="required"
                               placeholder="请输入主题标题"
                               class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">主题描述</label>
                    <div class="layui-input-block">
                        <textarea id="desc" name="desc" required lay-verify="required" placeholder="请输入主题描述"
                                  class="layui-textarea" rows="4"></textarea>
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">投票时间</label>
                    <div class="layui-input-block">
                        <input type="date" name="beginDate" id="beginDate" required lay-verify="required"
                               placeholder="开始时间" class="layui-input">
                        <span style="display: inline-block; width: 30px; text-align: center; color: #999;">至</span>
                        <input type="date" name="endDate" id="endDate" required lay-verify="required"
                               placeholder="结束时间" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">主题状态</label>
                    <div class="layui-input-block">
                        <input type="radio" name="status" value="0" title="未开始" checked>
                        <input type="radio" name="status" value="1" title="正在开始">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">投票选项</label>
                    <div class="layui-input-block">
                        <div id="optionsContainer">
                        </div>
                        <div id="addOptionBtn" onclick="addOption()"><i class="fa fa-plus-circle"></i> 添加选项</div>
                    </div>
                </div>
                <!-- HTML 部分保持不变 -->
                <div class="layui-input-block">
                    <div class="layui-upload">
                        <button type="button" class="layui-btn layui-btn-primary" id="uploadBtn">
                            <i class="fa fa-upload"></i> 上传封面图
                        </button>
                        <div class="layui-upload-list" style="margin-top: 15px;">
                            <img id="previewImg" src="" alt="主题封面预览"
                                 style="max-width: 300px; max-height: 200px; border-radius: 8px; display: none;">
                            <p id="uploadText" style="color: #999; margin-top: 10px;">
                                请上传一张图片作为主题封面（建议尺寸：600×400px）</p>
                        </div>
                        <input type="file" name="coverImage" id="coverImage" style="display: none;">
                    </div>
                </div>
            </div>

            <div class="form-footer">
                <button type="button" class="layui-btn layui-btn-primary" id="cancelBtn">取消</button>
                <button type="button" onclick="save()" class="layui-btn">保存主题</button>
                <button type="submit" id="sub" class="layui-btn"></button>
            </div>
        </form>
    </div>
</div>
<p style="color: red">${addTopicMessage}</p>
</body>
</html>

<script>
    var count = 0; // 初始选项数量

    $(document).ready(function () {
        // 初始化日期选择器
        layui.use('laydate', function () {
            var laydate = layui.laydate;
            laydate.render({
                elem: '#beginDate'
            });
            laydate.render({
                elem: '#endDate'
            });
        });

        // 初始化上传按钮
        // layui.use('upload', function () {
        //     var upload = layui.upload;
        //     upload.render({
        //         elem: '#uploadBtn',
        //         url: '/VoingSystem/admin/topic/uploadImage',
        //         accept: 'images',
        //         exts: 'jpg|png|gif|bmp',
        //         auto: false,
        //     })
        //
        // })

        //点击取消按钮 返回上一级
        $('#cancelBtn').click(function () {
            layer.confirm('确定取消添加主题吗？', {
                icon: 3,
                title: '提示'
            }, function (index) {
                // 这里添加退出登录的实际逻辑
                layer.msg('未保存主题', {icon: 1});
                setTimeout(function () {
                    // window.location.href = '/VoingSystem/admin/person/delPerson?pid=' + pid;
                    window.history.back()
                }, 1500);
                layer.close(index);
            })
        })


        // 主题封面上传按钮点击事件
        $('#uploadBtn').click(function () {
            // 触发文件输入框的点击，弹出选择对话框
            $('#coverImage').click();
        });

        // 主题封面文件选择事件
        $('#coverImage').change(function () {
            if (this.files && this.files[0]) {
                // 检查是否为图片文件
                const fileType = this.files[0].type;
                if (!fileType.startsWith('image/')) {
                    layer.msg('请上传图片文件', {icon: 5});
                    this.value = ''; // 清空文件选择
                    return;
                }

                // 检查文件大小（示例：限制10MB以内）
                const fileSize = this.files[0].size;
                if (fileSize > 10 * 1024 * 1024) {
                    layer.msg('图片大小不能超过10MB', {icon: 5});
                    this.value = ''; // 清空文件选择
                    return;
                }

                // 读取文件并预览
                const reader = new FileReader();
                reader.onload = function (e) {
                    // 显示预览图片
                    $('#previewImg').attr('src', e.target.result).show();
                    $('#uploadText').hide();

                    // 在控制台输出图片信息（可选）
                    console.log('主题封面已选择:', this.files[0].name);
                }.bind(this);
                reader.readAsDataURL(this.files[0]);
            }
        });
    })

    function save() {
        // 获取表单数据
        const beginDate = $('#beginDate').val();
        const endDate = $('#endDate').val();
        const now = new Date();
        const nowDate = formatDate(now);

        //判断标题是否为空
        if ($('#title').val() == '') {
            layer.msg('标题不能为空', {icon: 5});
            return;

        }

        //判断标题是否超过20个字
        if ($('#title').val().length > 20) {
            layer.msg('标题不能超过20个字', {icon: 5});
            return;

        }
        //判断描述是否为空
        if ($('#desc').val() == '') {
            layer.msg('描述不能为空', {icon: 5});
            return;

        }
        //判断描述是否超过50个字
        if ($('#desc').val().length > 50) {
            layer.msg('描述不能超过50个字', {icon: 5});
            return;

        }
        // 日期验证
        if (!validateDateRange(beginDate, endDate, nowDate)) return;

        // 选项验证
        const options = document.getElementsByName("option[]");
        if (!validateOptions(options)) return;

        // 图片验证

        // 封面照片验证
        if ($('#previewImg').attr('src') === '') {
            showError('封面照片不能为空');
            return;
        }


        const images = document.getElementsByName("images[]");
        if (!validateImages(options, images)) {
            return;
        }


        // 所有验证通过，提交表单
        $('#sub').click();
    }

    // 工具函数：格式化日期为 YYYY-MM-DD
    function formatDate(date) {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
    }

    // 工具函数：显示错误消息
    function showError(message) {
        layer.msg(message, {icon: 5});
    }

    // 验证日期范围
    function validateDateRange(beginDate, endDate, nowDate) {
        if (beginDate < nowDate) {
            showError('开始时间不能小于今天');
            return false;
        }

        if (endDate < nowDate) {
            showError('结束时间不能小于今天');
            return false;
        }

        if (beginDate >= endDate) {
            showError('开始时间必须小于结束时间');
            return false;
        }

        return true;
    }

    // 验证选项
    function validateOptions(options) {
        // 转换为数组以便使用数组方法
        const optionsArray = Array.from(options);

        // 检查是否有空选项
        if (optionsArray.some(option => option.value === '')) {
            showError('选项不能为空');
            return false;
        }

        // 检查选项是否重复
        const optionValues = optionsArray.map(option => option.value);
        const uniqueValues = [...new Set(optionValues)];

        if (optionValues.length !== uniqueValues.length) {
            showError('选项不能重复');
            return false;
        }

        // 检查选项数量
        if (optionsArray.length > 5) {
            showError('选项不能超过5个');
            return false;
        }

        if (optionsArray.length < 2) {
            showError('选项不能少于2个');
            return false;
        }

        return true;
    }

    // 验证图片
    function validateImages(options, images) {
        if (images.length !== options.length) {
            showError('选项图片数量必须等于选项数量');
            return false;
        }

        for (let i = 0; i < images.length; i++) {
            if (images[i].files.length === 0) {
                showError('选项图片数量必须填写');
                return false;
            }
        }
        return true;
    }


    // 添加选项
    function addOption() {
        let optionsContainer = $('#optionsContainer');
        let html = `
        <div class="option-item">
            <span class="option-index">` + (++count) + `</span>
            <input type="text" name="option[]" required lay-verify="required"
                   placeholder="请输入选项内容" class="layui-input option-input">
            <div class="option-upload">
                <button type="button" onclick="selectFile(this)" class="layui-btn layui-btn-primary option-upload-btn">
                    <i class="fa fa-upload"></i>上传图片
                </button>
                <img src="" alt="选项图片预览" class="option-preview">
                <button type="button" onclick="deleteImage(this)" class="layui-btn layui-btn-danger delete-image-btn" style="display: none;">
                    <i class="fa fa-trash"></i>删除图片
                </button>
                <input type="file" name="images[]" class="option-file-input" style="display: none;">
            </div>
            <span class="delete-option" onclick="delOption(this)"><i class="fa fa-times"></i></span>
        </div>`;
        optionsContainer.append(html);
    }

    function selectFile(btn) {
        const fileInput = btn.parentNode.querySelector('.option-file-input');
        fileInput.name = 'images[]';
        const uploadBtn = btn;
        const previewImg = btn.parentNode.querySelector('.option-preview');
        const deleteImgBtn = btn.parentNode.querySelector('.delete-image-btn');

        fileInput.click();

        fileInput.onchange = function () {
            if (this.files && this.files[0]) {
                const reader = new FileReader();
                reader.onload = function (e) {
                    previewImg.src = e.target.result;
                    previewImg.style.display = 'inline-block';
                    uploadBtn.style.display = 'none'; // 隐藏上传按钮
                    deleteImgBtn.style.display = 'inline-block'; // 显示删除按钮
                };
                reader.readAsDataURL(this.files[0]);
            }
        };
    }

    // 删除图片（保留选项）
    function deleteImage(btn) {
        const previewImg = btn.parentNode.querySelector('.option-preview');
        const uploadBtn = btn.parentNode.querySelector('.option-upload-btn');
        const fileInput = btn.parentNode.querySelector('.option-file-input');

        // 重置图片和文件输入
        previewImg.src = '';
        previewImg.style.display = 'none';
        fileInput.value = ''; // 清空文件选择

        // 恢复上传按钮，隐藏删除按钮
        uploadBtn.style.display = 'inline-block';
        btn.style.display = 'none';
    }

    // 删除选项（整个选项）
    function delOption(option) {
        $(option).closest('.option-item').remove();
        count--;

        // 更新剩余选项的索引
        $('.option-item').each(function (index) {
            $(this).find('.option-index').text(index + 1);
        });
    }

    function logout() {
        layer.confirm('确定要退出登录吗？', {
            icon: 3,
            title: '提示'
        }, function (index) {
            // 这里添加退出登录的实际逻辑
            layer.msg('已成功退出登录', {icon: 1});
            setTimeout(function () {
                window.location.href = '/VoingSystem/logout';
            }, 1500);
            layer.close(index);
        })
    }
</script>